<?php
namespace app\home\controller;
use stdClass;
use think\Request;
use think\Loader;
use app\home\service\NotifyService;
use app\home\service\OrderService;
class PayWeb800020 extends BasePay
{
    const APP_ID = '2021003173698541';
    const PUBLIC_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuK3SPyTC+Pvv3gqYiTH5UvUsayTS7swNBQjvbfhDZakOa+GlO7AASeIoZ9jSdSKEOxurOnAvXA2YM5pZxzM3xsXtP2ibCIFt96v1pAsuny3v9yvYYD0MC6gpoSCgQPjAFLvqOEnqUYVjkE6J9kGtjuMiO7X20LZL5TCh1EnT39u0izH35gtkZzMPLR6A/1v6J4gNizDSWofSO8YRuTa3LJK09XsRGP2Z9nnetGcZJMKdlub4SlcFnwoIFp5COKqmes0qJMAerymn00DgaOeenNPQId5YcnQtTd3kneRS+GB52eRR+Z1rjkg14lTO4vwDdXzOd5wgXm7sUGWhsNH/NQIDAQAB';
    const PRIVATE_KEY = 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCFeTWE0+TghQKSok6ONKD765UlK4sBekyxUlAUnRnUI7cc+1V/g6g3g/WIOguxDdvB0eK7Aih3H2apz5rl98JMGELA+QshxlG5ennKXMis/WwTydioY0jX8d7fTTciJ//jgsii3O4yQy5UHzJUZAoDa6SmBZ4b94dy2kXDo3Qap3G78q6Gqyz/7uthOSGm1G/i0ptxQiV8rbGuOK3puxBIBS1d4NIE1eXQBuR8bBSA0tjeZiDwhCVHdRtaJxiAJbzpDu5BowRpIbucJ+stTwwZ25CH1uJLToYIizyZl2A3GJuZVoMPMIDe3x4LsEAIrnvljd3cQanCl9t4LxbdSEu7AgMBAAECggEAdjNvN+BG0qY4Lw9ZrgnhfveUL0SuZ3KdNHOGw5qU4w91/E5/2tsHP5K3ABsXe4agVLbAqYgxubyvODbIIFwXTzg09ZwXRaPRgAZ8kL82YCxVZ/jay9SRD9v82ZgR+UefDyYk9EXfE9f20TyHX8DwNTNArl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adefishing.com/home/payWeb800020/notify';

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }


    public function order()
    {
        parent::order();
   
        $http_response_header = $this->alipay_pay_handle($this->order_array['goods_name'],$this->order_array['id'], $this->order_array['amount']);
        $arr['code'] = 'success';
        $arr['order'] = $this->order_array['id'];
        $arr['data'] = config('alipay.gatewayUrl')."?".$http_response_header;
        $arr['total_amount'] = $this->order_array['amount'];

        exit(json_encode($arr,JSON_UNESCAPED_SLASHES));
    }

    private function alipay_pay_handle($subject, $order_id, $total_price)
    {
        /*支付宝支付接口*/
        Loader::import('alipay.aop.AopClient');
        Loader::import('alipay.aop.request.AlipayTradePagePayRequest');
        $aop = new \AopClient();
        $aop->gatewayUrl = config('alipay.gatewayUrl');


        $aop->appId = self::APP_ID; //开发者appid
        $aop->rsaPrivateKey = self::PRIVATE_KEY;
        $aop->alipayrsaPublicKey = self::PUBLIC_KEY;

        $aop->apiVersion = '1.0';
        $aop->format = "json";
        $aop->charset = "utf-8";
        $aop->signType = "RSA2";

        $object = new stdClass();
        $object->out_trade_no = $order_id;
        $object->total_amount =$total_price;
        $object->subject = $subject;
        $object->product_code ='FAST_INSTANT_TRADE_PAY';
        // $object->time_expire = date('Y-m-d H:i:s');
        $json = json_encode($object);
        $request = new \AlipayTradePagePayRequest();

        $request->setNotifyUrl(self::NOTIFY_URL);
        $request->setReturnUrl('https://h5c.hemayouxi.com/ClassicArcadeFishing/gfindex.htmll');
        $request->setBizContent($json);
        $result = $aop->pageExecute ( $request); 
        return $result;
    }

    public  function notify(){
        parent::notify();
        $params = Request::instance()->param();
        Loader::import('alipay.aop.AopClient');
        $aop = new \AopClient();
        $aop->alipayrsaPublicKey = self::PUBLIC_KEY;
        $flag = $aop->rsaCheckV1($params, NULL, "RSA2");
        mylog($flag);
        try {
            parent::notify();
            $params = Request::instance()->param();
            Loader::import('alipay.aop.AopClient');
            $aop = new \AopClient();
            $aop->alipayrsaPublicKey = self::PUBLIC_KEY;
            $flag = $aop->rsaCheckV1($params, NULL, "RSA2");
            mylog($flag);
            if(!$flag){
                throw new \Exception('$flag false');
            }
            if($params['trade_status'] == 'TRADE_SUCCESS' or $params['trade_status'] == 'TRADE_FINISHED'){
                $tradeLog = (new \app\home\model\TradeLog)->where(['id' => $params['out_trade_no']])->find();
                if (empty($tradeLog)) {
                    throw new \Exception('订单不存在');
                }
                if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                    mylog("Pay800020 订单已经处理过了 订单id" . $tradeLog['id']);
                    return 'success';
                }
                
                if ($tradeLog['amount'] != $params['total_amount']) {
                    throw new \Exception('total_amount false');
                }
                //发货
                $notifyService = new NotifyService();
                if ($notifyService->notifyProcess($tradeLog) == false) {
                    throw new \Exception('notifyProcess false');
                }
                return 'success';
            }else{
                throw new \Exception('trade_status false');
            }
           
        } catch (\Exception $exception) {
            mylog('Pay800020-error:' . $exception->getMessage() . ' line:' . $exception->getLine() . ' file:' . $exception->getFile());
            exit('FAIL');
        }
    }
}
